package com.chuangke.metadata.function;

import cn.hutool.core.util.StrUtil;
import com.chuangke.metadata.service.SysBillSerialService;
import com.chuangke.common.utils.SpringContextUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SnGenFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "sn";
    }

    /**
     * 生成流水号
     *
     * @param env
     * @param arg1 业务id
     * @param arg2 流水依据
     * @param arg3 流水号长度
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        String modelId = (String) arg1.getValue(env);//流水依据
        String snAccordingTo = FunctionUtils.getStringValue(arg2, env);//流水依据
        Long length = (Long) arg3.getValue(env);

        SysBillSerialService sysBillSerialService = (SysBillSerialService) SpringContextUtil.getBean(SysBillSerialService.class);
        String serial = sysBillSerialService.nextSerial(modelId, snAccordingTo);

        return new AviatorString(StrUtil.fillBefore(serial + "", '0', length.intValue()));
    }
}
